package com.yu.mall.service;

import com.yu.mall.entity.Captcha;
import com.yu.mall.exception.ServiceException;
import com.yu.mall.mapper.CaptchaMapper;
import com.yu.mall.util.ResultUtils;
import com.yu.mall.vo.ResultVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CaptchaService {

    @Value("${spring.profiles.active}")
    private String profiles;

    private final static String DEFAULT_CODE = "0000";

    private final int TTL = 60 * 5;

    private final static String  MSG_CONTENT = "(普陀区中心医院注册码),请在5分钟中内完成操作。如非本人操作，请忽略。";

    @Autowired
    private CaptchaMapper captchaMapper;


    public ResultVO send(String phone){
        String code = RandomStringUtils.randomNumeric(4);
        if("dev".equals(profiles) || "test".equals(profiles)){
            code = DEFAULT_CODE;
        }

        //发送验证码
        Date date = DateUtils.addSeconds(new Date(), 10);
        if(!"dev".equals(profiles) && !"test".equals(profiles)){
            String content = code + MSG_CONTENT;
            //TODO 短信发送接口
        }

        Captcha captcha = new Captcha();
        captcha.setPhone(phone);
        //先清除之前的数据
        captchaMapper.delete(captcha);
        captcha.setCode(code);
        captcha.setCreateTime(new Date());
        captcha.setUpdateTime(new Date());
        captcha.setTtl(TTL);
        captchaMapper.insertSelective(captcha);

        return ResultUtils.success();
    }

    public boolean validator(String phone,String code) throws ServiceException {
        Captcha captcha = new Captcha();
        captcha.setCode(code);
        captcha.setPhone(phone);
        captcha = captchaMapper.selectOne(captcha);
        if(captcha == null){
            return false;
        }
        Date createTime = captcha.getCreateTime();
        Date date = DateUtils.addSeconds(createTime, captcha.getTtl());
        if(date.compareTo(new Date()) == -1){
            throw new ServiceException("验证码已过期");
        }
        return true;
    }

    public ResultVO list() {
        List<Captcha> captchas = captchaMapper.queryList();
        return ResultUtils.success(captchas);
    }
}
